import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from "element-plus";
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import OrderView from '../views/OrderView.vue'
import FoodView from '../views/FoodView.vue'
import CommentView from '../views/CommentView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/order',
      name: 'order',
      component: OrderView,
    },
    {
      path: '/food',
      name: 'food',
      component: FoodView,
    },
    {
      path: '/comment',
      name: 'comment',
      component: CommentView,
    }
  ],
})

router.beforeEach((to, from, next) => {
  const publicPages = ['/'];  // 不需要身份验证的路由
  let authRequired = !publicPages.includes(to.path); // 检查即将进入的页面是否需要验证
  let loggedIn = JSON.parse(localStorage.getItem('user')); // 检测是否已登录

  if(loggedIn) {
    let loginTime = new Date(loggedIn.data.createTime);
    let currentTime = new Date();
    let timeDifference = currentTime - loginTime;
    let towHours = 2* 60 * 60 * 1000;

    if(timeDifference > towHours) {
      localStorage.removeItem('user');
      ElMessage.error("登录超时，请重新登录");
      return next('/');
    }
  }

  if (authRequired && !loggedIn) { // 如果需要验证且没有登录
    ElMessage.error("用户未登录，请进行登录");
    return next('/'); // 重定向到登录页面
  }
  next(); // 如果不需要验证，或者已经登录，就正常导航
})

export default router
